﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SC
{
    /// <summary>
    /// 服务端每秒广播ip给客户端 格式为 headstr+ip
    /// </summary>
    public class BroadCastServer
    {
        
        public static void Start(Common.ServerProfile serverProfile)
        {
            System.Threading.Thread threadBroadCast = new System.Threading.Thread(new ParameterizedThreadStart(BroadCast));
            threadBroadCast.IsBackground = true;
            threadBroadCast.Start(serverProfile);
        }

        private static void BroadCast(object obj)
        {
            Common.ServerProfile serverProfile = obj as Common.ServerProfile;

            byte[] buf = Encoding.Default.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(serverProfile));

            System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));
            System.Net.IPEndPoint endpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(Common.LocalIP.broadcastIpstring), Common.LocalIP.broadcastPort);

            while (true)
            {
                client.Send(buf, buf.Length, endpoint);
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}
